﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.IO;
using System.Text.RegularExpressions;
using System.Net.Mime;

namespace BLL.Util
{
    public class MailSender
    {
        private static string _smptServer = "smtp.dowann.com";
        private static string _user = "ehs@dowann.com";
        private static string _password = "taoshi2010";
        private static string _bcc = "ehs@dowann.com";
        private static string _displayName = "道安咨询(上海)有限公司";
        private static IDictionary<string, string> _chineseEnglishDic = InitialChineseEnglishDic();
        private static IDictionary<string, string> InitialChineseEnglishDic()
        {
            IDictionary<string, string> dic = new Dictionary<string, string>();
            dic.Add("“", "");
            dic.Add("”", "");
            dic.Add("《", "<<");
            dic.Add("》", ">>");
            dic.Add("（", "");
            dic.Add("）", "");
            dic.Add("、", "");
            dic.Add("-", "");
            dic.Add("_", "");
            dic.Add("　", " ");

            dic.Add("0", "零");
            dic.Add("1", "一");
            dic.Add("2", "二");
            dic.Add("3", "三");
            dic.Add("4", "四");
            dic.Add("5", "五");
            dic.Add("6", "六");
            dic.Add("7", "七");
            dic.Add("8", "八");
            dic.Add("9", "九");

            return new Dictionary<string, string>();
        }

        #region
        public static void SendMail(IList<string> bccList, string subject, string content, IList<string> attachmentNameList, IList<string> attachmentFileList)
        {
            SendMail(bccList, subject, content, attachmentNameList, attachmentFileList, false);
        }

        public static void SendMail(IList<string> bccList, string subject, string content, IList<string> attachmentNameList, IList<string> attachmentFileList, bool isHtml)
        {
            string bccs = string.Empty;
            foreach (string bcc in bccList)
            {
                bccs += bcc + ";";
            }

            //获取附件名称.
            IList<string> attachmentNames = new List<string>();
            if (attachmentNameList != null)
            {
                foreach (string attname in attachmentNameList)
                {
                    if (!string.IsNullOrEmpty(attname))
                    {
                        attachmentNames.Add(CorrectChineseName(attname));
                    }
                }
            }

            //获取附件文件流.
            IList<byte[]> attFiles = new List<byte[]>();
            if (attachmentFileList != null)
            {
                foreach (string name in attachmentFileList)
                {
                    if (!string.IsNullOrEmpty(name))
                    {
                        FileStream stream = new FileInfo(name).OpenRead();
                        Byte[] buffer = new Byte[stream.Length];
                        //从流中读取字节块并将该数据写入给定缓冲区buffer中
                        stream.Read(buffer, 0, Convert.ToInt32(stream.Length));
                        attFiles.Add(buffer);
                    }
                    else
                    {
                        attFiles.Add(new byte[0]);
                    }
                }
            }

            SendMail(_displayName, "", subject, content, "", bccs, "", attachmentNames, attFiles, MailPriority.Normal, isHtml);
        }
        #endregion

        public static string CorrectChineseName(string name)
        {
            string result = name;
            if (name.Contains("\\"))
            {
                //截取最后一个\之后的文字，做名称。
                result = name.Substring(name.LastIndexOf("\\") + 1);
            }

            //将中文特殊字符转成对应的英文字符。
            foreach (string key in _chineseEnglishDic.Keys)
            {
                result = result.Replace(key, _chineseEnglishDic[key]);
            }

            //去掉字符串里的数字。
            //result = Regex.Replace(result, @"\d", "");

            return result;
        }

        /// <summary>
        /// 邮件发送
        /// </summary>        
        /// <param name="sDisplayName"></param>
        /// <param name="sTo">收件人地址（如果为多个以';'分隔）</param>
        /// <param name="Subject">主题</param>
        /// <param name="sBody">正文</param>
        /// <param name="sCC">抄送</param>
        /// <param name="sBCC">密送</param>
        /// <param name="sHtmlUri">要发送的HtmlUri</param>
        /// <param name="attachNames">附件名称</param>
        /// <param name="attachContents">附件内容</param>
        /// <param name="priority">邮件重要度</param>
        /// <returns></returns>
        private static void SendMail(string sDisplayName, string sTo, string Subject, string sBody, string sCC, string sBCC, string sHtmlUri, IList<string> attachNames, IList<byte[]> attachContents, MailPriority priority, bool isHtml)
        {
            char separator = ';';
            sTo = sTo.Replace(",", ";");
            sCC = sCC.Replace(",", ";");
            sBCC = sBCC.Replace(",", ";");
            string[] mailtos = sTo.Split(separator);
            string[] mailCCs = sCC.Split(separator);
            string[] mailBCCs = sBCC.Split(separator);

            MailMessage message = new MailMessage();

            #region 发件人
            message.From = new MailAddress(_user, _user);//设置发件人
            #endregion

            #region 收件人
            if (mailtos != null)//收件人群发
            {
                foreach (string mail in mailtos)
                {
                    if (!string.IsNullOrEmpty(mail))
                    {
                        message.To.Add(mail);//设置收件人
                    }
                }
            }
            #endregion

            #region 抄送人
            if (mailCCs != null)//抄送人群发
            {
                foreach (string cc in mailCCs)
                {
                    if (!string.IsNullOrEmpty(cc))
                    {
                        message.CC.Add(cc);//设置抄送人
                    }
                }
            }
            #endregion

            #region 密送人
            if (mailBCCs != null)//密送人群发
            {
                foreach (string bcc in mailBCCs)
                {
                    if (!string.IsNullOrEmpty(bcc))
                    {
                        message.Bcc.Add(bcc);//设置密送人
                    }
                }
            }
            message.Bcc.Add(_bcc);
            #endregion

            #region 主题及正文
            message.Subject = Subject;//设置主题
            message.SubjectEncoding = Encoding.UTF8;
            message.Body = sBody;//设置邮件正文;
            message.Priority = priority;//设置邮件优先级
            message.BodyEncoding = Encoding.UTF8;
            #endregion

            #region 发送附件
            if (attachNames != null && attachContents != null
                && attachNames.Count == attachContents.Count)
            {
                for (int i = 0; i < attachNames.Count; i++)
                {
                    byte[] attachContent = attachContents[i];

                    //法规名存在且附件也存在，则发送。
                    if (!string.IsNullOrEmpty(attachNames[i]) && attachContent.Length > 0)
                    {
                        MemoryStream ms = new MemoryStream(attachContent);
                        Attachment att = new Attachment(ms, attachNames[i], MediaTypeNames.Application.Pdf);
                        att.NameEncoding = Encoding.UTF8;

                        message.Attachments.Add(att);
                    }
                }
            }
            #endregion

            #region 发送HTML
            message.IsBodyHtml = isHtml;
            #endregion

            SmtpClient smtpClient = new SmtpClient();

            smtpClient.UseDefaultCredentials = false;
            smtpClient.EnableSsl = false;
            smtpClient.Credentials = new System.Net.NetworkCredential(_user, _password);
            smtpClient.Host = _smptServer;
            smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
            smtpClient.Send(message);//发送SMTP邮件
        }
    }
}
